package leo.mystudy.leetcode;

import java.util.Date;

/**
 * 最长回文子串
 *
 * @author chao.li@quvideo.com
 * @date 2018/6/29 09:45
 */
public class LongestPalindrome {
    //    给定一个字符串 s，找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
//
//    示例 1：
//
//    输入: "babad"
//    输出: "bab"
//    注意: "aba"也是一个有效答案。
//    示例 2：
//
//    输入: "cbbd"
//    输出: "bb"
    public static void main(String[] args) {
        long start = new Date().getTime();
        String s = "slvafhpfjpbqbpcuwxuexavyrtymfydcnvvbvdoitsvumbsvoayefsnusoqmlvatmfzgwlhxtkhdnlmqmyjztlytoxontggyytcezredlrrimcbkyzkrdeshpyyuolsasyyvxfjyjzqksyxtlenaujqcogpqmrbwqbiaweacvkcdxyecairvvhngzdaujypapbhctaoxnjmwhqdzsvpyixyrozyaldmcyizilrmmmvnjbyhlwvpqhnnbausoyoglvogmkrkzppvexiovlxtmustooahwviluumftwnzfbxxrvijjyfybvfnwpjjgdudnyjwoxavlyiarjydlkywmgjqeelrohrqjeflmdyzkqnbqnpaewjdfmdyoazlznzthiuorocncwjrocfpzvkcmxdopisxtatzcpquxyxrdptgxlhlrnwgvee";
        //String s="bb";
        for (int i = 0; i < 1000; i++) {
            System.out.println(new LongestPalindrome().longestPalindrome(s));
        }
        long end = new Date().getTime();
        System.out.println("耗时：" + (end - start) + "毫秒");
    }

    public String longestPalindrome(String s) {
        if (s.length() <= 1) {
            return s;
        }
        String result = "";
        for (int i = 0; i < s.length(); i++) {
            // 考虑到奇回文和偶回文两种情况，取两次比较得较大值
            int l1 = getPalindromeLength(s, i, i);
            int l2 = getPalindromeLength(s, i, i + 1);
            int max = Integer.max(l1, l2);
            if (max > result.length()) {
                int start = i - (max - 1) / 2;
                int end = start + max;
                result = s.substring(start, end);
            }
        }
        return result;
    }

    /**
     * 得到局部最长回文长度
     *
     * @param s
     * @param left
     * @param right
     * @return
     */
    private int getPalindromeLength(String s, int left, int right) {
        int length = 1;
        while (left >= 0 && right <= s.length() - 1 && s.charAt(left) == s.charAt(right)) {
            length = right - left + 1;
            left--;
            right++;
        }
        return length;
    }

}
